<template>
<div style="text-align: center;margin-top: 100px">
  <div style="width: 92%;margin-left: 4%">
    <Button :loading="buttonLoading" v-show="show" size="large" type="success" @click="weChatLogin" long>确认登录</Button>
    <div v-show="!show" style="font-size: 20px">页面将在 {{ time }} s后关闭</div>
  </div>
</div>
</template>

<script>
import { getWeChatUserInfo } from '../../api/user'
export default {
  name: 'confirm',
  data () {
    return {
      code: '',
      id: '',
      show: true,
      time: 0,
      setTimeOutTimer: 0,
      buttonLoading: false
    }
  },
  methods: {
    init () {
      console.log(this.$route, 111)
      const w = location.href.indexOf('?')
      const j = location.href.indexOf('#')
      let href = window.location.href
      // 处理微信回调url
      if (w !== -1 && j > w) {
        href = location.href.substr(0, w) + location.href.substr(j, location.href.length) + location.search
        console.log('href', href)
        location.href = href
      }
    },
    weChatLogin () {
      this.time = 3
      this.buttonLoading = true
      this.code = this.$route.query.code
      this.id = this.$route.query.state
      console.log('code', this.code)
      let data = {
        code: this.code,
        id: this.id
      }
      getWeChatUserInfo(data).then(ret => {
        if (ret.data.errcode === 0) {
          let data = ret.data.data
          if (data.errcode === 0) {
            this.$Message.success(ret.data.errmsg)
          } else if (data.errcode === 9333) {
            this.$Message.error(ret.data.errmsg)
          }
        } else {
          this.buttonLoading = false
          this.$Message.error(ret.data.errmsg)
        }
        this.show = false
        this.buttonLoading = false
        this.setTimeOutTimer = setInterval(() => {
          this.time--
          console.log(this.time)
          console.log(this.setTimeOutTimer)
          if (this.time === 0) {
            WeixinJSBridge.call('closeWindow')
            clearInterval(this.setTimeOutTimer)
          }
        }, 1000)
      })
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style scoped>
</style>
